package cn.virens.common.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.stream.IntStream;

public class JSONUtil {

    public static <T> T toObj(JSONObject object, Class<T> clazz) {
        return object != null ? object.to(clazz) : null;
    }

    public static <T> List<T> toList(JSONArray array, Class<T> clazz) {
        return array != null ? array.toList(clazz) : new ArrayList<>();
    }

    public static <T> T getObj(JSONArray array, int index, Class<T> clazz) {
        return array != null ? array.getObject(index, clazz) : null;
    }

    public static <T> T getObj(JSONObject object, String key, Class<T> clazz) {
        return object != null ? object.getObject(key, clazz) : null;
    }

    public static <T> List<T> getList(JSONArray array, int index, Class<T> clazz) {
        return JSONUtil.toList(array.getJSONArray(index), clazz);
    }

    public static <T> List<T> getList(JSONObject object, String key, Class<T> clazz) {
        return JSONUtil.toList(object.getJSONArray(key), clazz);
    }

    public static <T> void forEach(JSONArray array, Class<T> clazz, BiConsumer<T, Integer> consumer) {
        IntStream.range(0, array.size()).forEach(i -> consumer.accept(getObj(array, i, clazz), i));
    }

    public static <T> void forEach(JSONObject object, Class<T> clazz, BiConsumer<T, String> consumer) {
        StreamUtil.stream(object.keySet()).forEach(k -> consumer.accept(getObj(object, k, clazz), k));
    }

}
